﻿using System;
using System.Windows.Forms;

namespace HexDisplay
{
    public partial class WinOff : Form
    {
        private int offset = -1;
        private HexDisplay hex;
        private bool isHex = false;
        private bool IsHexChar(char c)
        {
            if(char.IsDigit(c))
            {
                return true;
            }
            switch(c)
            {
                case 'a':
                case 'A':
                case 'b':
                case 'B':
                case 'c':
                case 'C':
                case 'd':
                case 'D':
                case 'e':
                case 'E':
                case 'f':
                case 'F':
                    return true;
                default:
                    return false;
            }
        }

        public WinOff(HexDisplay ahex)
        {
            hex = ahex;
            InitializeComponent();
            offsetLabel.Text = "偏移范围[0 - " + hex.OpenedFile.Length + "]";
        }

        private void offset_TextChanged(object sender, EventArgs e)
        {
            TextBox tb = (TextBox)sender;
            if(tb.Text.Length == 0)
            {
                return;
            }
            int last = tb.Text.Length - 1;
            if(tb.Text[0] != '0')
            {
                isHex = false;
                if(!char.IsDigit(tb.Text[last]))
                {
                    tb.Text = tb.Text.Substring(0, last);
                }
            }
            else
            {
                if(last >= 1)
                {
                    if(tb.Text[1] == 'x' || tb.Text[1] == 'X')
                    {
                        isHex = true;
                        if(last > 1 && !IsHexChar(tb.Text[last]))
                        {
                            tb.Text = tb.Text.Substring(0, last);
                        }
                    }
                    else
                    {
                        isHex = false;
                        if(!char.IsDigit(tb.Text[last]))
                        {
                            tb.Text = tb.Text.Substring(0, last);
                        }
                    }
                }
            }
        }

        private void jumpButton_Click(object sender, EventArgs e)
        {
            offset = -1;
            if(isHex)
            {
                offset = int.Parse(offsetTextBox.Text.Substring(2), System.Globalization.NumberStyles.HexNumber);
            }
            else
            {
                offset = int.Parse(offsetTextBox.Text);
            }
            if(offset >= 0)
            {
                hex.DisplayFileAtOffset(offset);
            }
        }
    }
}
